import { FC, useEffect, useRef } from "react";
import { init, type EChartsType } from "echarts";

interface ColumnProps {
  // 数据源
  data: any[];
  // x坐标使用那个字段
  xField: string;
  // y坐标使用那个字段
  yField: string;
  label?: {
    position: string;
    style: any;
  };
}

const Column: FC<ColumnProps> = ({ data, xField, yField, label }) => {
  const box = useRef<HTMLDivElement>(null);
  const ins = useRef<EChartsType>();

  useEffect(() => {
    // 初始化 ECharts
    if (!ins.current) {
      ins.current = init(box.current!);
    }

    ins.current?.setOption({
      tooltip: {},
      xAxis: { data: data.map((item) => item[xField]) },
      yAxis: {},
      series: [
        {
          type: "bar",
          data: data.map((item) => item[yField]),
          label: label
            ? {
                show: true,
                color: label.style.fill || "#fff",
                position: label.position || "inside",
              }
            : undefined,
        },
      ],
    });
  }, [data]);

  return <div ref={box} style={{ width: "100%", height: 400 }}></div>;
};

export default Column;
